import ajax from './api/ajax';
import { RawApi } from './api/wrapper';

/**
 * 新版上传文件接口的包装
 * @param         file: 文件内容
 * @returns       fileId: 文件id
 */
export async function uploadLargeFile(param: {
  file: File;
}): Promise<{ fileId: string }> {
  const { file } = param;

  const { fileId, signedUrl } = await RawApi.fetch<{
    fileId: string;
    signedUrl: string;
  }>({
    method: 'POST',
    url: '/api/media/api/v1/media/getSignatureUrl',
    data: {
      fileName: file.name,
    },
  });
  if (!(fileId && signedUrl)) {
    throw new Error('[0]上传签名信息错误');
  }

  await ajax.ajax({
    method: 'PUT',
    url: signedUrl,
    data: {
      body: file,
    },
    headers: {
      'Content-Type': 'text/plain',
    },
  });

  await RawApi.fetch({
    method: 'GET',
    url: '/api/media/api/v1/media/callback',
    query: {
      id: fileId,
    },
  });

  return {
    fileId,
  };
}
